#!/bin/bash

# 代码行数统计脚本
# 统计SystemVerilog/Verilog源代码文件的行数

echo "========================================"
echo "代码行数统计工具"
echo "========================================"
echo ""

# 定义颜色
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 统计函数
count_lines() {
    local pattern=$1
    local description=$2
    local files=$(find . -name "$pattern" 2>/dev/null)
    
    if [ -z "$files" ]; then
        echo -e "${YELLOW}$description: 0 个文件${NC}"
        return
    fi
    
    local total_lines=0
    local file_count=0
    local code_lines=0
    local comment_lines=0
    local blank_lines=0
    
    for file in $files; do
        if [ -f "$file" ]; then
            ((file_count++))
            local lines=$(wc -l < "$file")
            ((total_lines+=lines))
            
            # 统计代码行（非空非注释）
            local code=$(grep -v "^\s*$" "$file" | grep -v "^\s*//" | grep -v "^\s*/\*" | grep -v "^\s*\*" | wc -l)
            ((code_lines+=code))
            
            # 统计空行
            local blank=$(grep -c "^\s*$" "$file")
            ((blank_lines+=blank))
            
            # 统计注释行（简化统计）
            local comments=$(grep -c "^\s*//" "$file")
            ((comment_lines+=comments))
        fi
    done
    
    echo -e "${GREEN}$description:${NC}"
    echo "  文件数量: $file_count"
    echo "  总行数: $total_lines"
    echo "  代码行: $code_lines"
    echo "  注释行: $comment_lines (仅单行注释)"
    echo "  空行: $blank_lines"
    echo ""
}

# 统计各类文件
count_lines "*.sv" "SystemVerilog 文件 (*.sv)"
count_lines "*.svh" "SystemVerilog 头文件 (*.svh)"
count_lines "*.v" "Verilog 文件 (*.v)"
count_lines "*.vh" "Verilog 头文件 (*.vh)"

# 统计总计
echo "========================================"
echo -e "${BLUE}总体统计:${NC}"

all_files=$(find . \( -name "*.sv" -o -name "*.svh" -o -name "*.v" -o -name "*.vh" \) 2>/dev/null)
total_files=$(echo "$all_files" | grep -v "^$" | wc -l)
total_lines=$(cat $all_files 2>/dev/null | wc -l)
total_code=$(cat $all_files 2>/dev/null | grep -v "^\s*$" | grep -v "^\s*//" | grep -v "^\s*/\*" | grep -v "^\s*\*" | wc -l)
total_blank=$(cat $all_files 2>/dev/null | grep -c "^\s*$")
total_comments=$(cat $all_files 2>/dev/null | grep -c "^\s*//")

echo "  总文件数: $total_files"
echo "  总行数: $total_lines"
echo "  总代码行: $total_code"
echo "  总注释行: $total_comments (仅单行注释)"
echo "  总空行: $total_blank"
echo ""

# 按目录统计
echo "========================================"
echo -e "${BLUE}按目录统计:${NC}"
echo ""

for dir in $(find . -type d | grep -v "^\.$" | sort); do
    dir_files=$(find "$dir" -maxdepth 1 \( -name "*.sv" -o -name "*.svh" -o -name "*.v" -o -name "*.vh" \) 2>/dev/null)
    if [ -n "$dir_files" ]; then
        dir_lines=$(cat $dir_files 2>/dev/null | wc -l)
        dir_file_count=$(echo "$dir_files" | wc -l)
        echo -e "${YELLOW}$dir${NC}: $dir_file_count 个文件, $dir_lines 行"
    fi
done

echo ""
echo "========================================"
echo "统计完成！"
echo "========================================"
